
MAX_LINE_BYTE = 65535


class State:
    IDLE = 0
    SHAKEHAND = 1
    BINARY = 2

class Info:
    pass

class StateProcess():

    
    def __init__(self, handler):
        self.state = State.IDLE
        self.handler = handler
        self.globalInfo = Info()
        self.stateInfo = Info()
        self.stop = False
    
    def process(self):
        while True:
            line = readline(self.handler.request)
            if line == None:
                return
            tag, value = parseline(line)
            self.stateInfo.tag = tag
            self.stateInfo.value = value
            func = StateProcess.funcMap[self.state]
            func(self)
        
            
    
    def idleFunc(self):
        print("idle process")
        tag = self.stateInfo.tag
        value = self.stateInfo.value
        if (tag == "VER"):
            try:
                self.globalInfo.version = int(value)
            except:
                self.globalInfo.version = 1
            print("got ver:" + str(self.globalInfo.version))
        elif (tag == "ECHO"):
            self.sendstring("ECBK:" + value)
        elif (tag == "BYE"):
            self.stop = True
        elif (tag == "BIN"):
            self.state = State.BINARY
            self.binaryFunc()    
        self.stateInfo = Info()


    def shakehandFunc(self):
        pass
    
    def binaryFunc(self):
        pass
    
    def sendstring(self, string):
        self.handler.request.send(string.encode("ascii"))
        
        
    funcMap = {
           State.IDLE : idleFunc,
           State.SHAKEHAND : shakehandFunc,
           State.BINARY : binaryFunc,
           }

def readline(socket):
    linebuf = []
    while True:
        b = socket.recv(1)
        if b == b'':
            return None
        c = b.decode("ascii")
        if  c == '\n':
            return "".join(linebuf)
        else:
            linebuf.append(c)
            
def parseline(line):
    idx = line.find(":")
    if idx == -1:
        return None, None
    else:
        return line[:idx].strip(), line[idx+1:].strip()